<?php
namespace app\api\controller\v1;
include_once APP_PATH . 'api/common.php';
use app\admin\model\School as SchoolModel;
use app\admin\model\Column;
use app\common\controller\Api;
use think\Db;
use think\Request;
use app\admin\model\Coursetable;
use app\admin\model\Ocation;
use app\admin\model\Article;
use app\admin\model\Favorites;
use app\api\controller\v1\Event;

class School extends Api
{

    protected $noNeedLogin=['lists','read'];
    protected $noNeedRight = ['lists','read'];


    // 获取学校列表的方法
    public function lists()
    {
        // 获取请求参数
        $name = input('get.name', '');  // 默认空字符串，如果没有提供 'q' 参数
        $id = input('get.id', 0);
        $page = input('get.page', 1);  // 默认第一页，如果没有提供 'page' 参数
        $pagesize=input('get.pagesize', 10);

        // 实例化 Api 模块的学校模型
        $schoolModel = new SchoolModel();

        // 构建查询条件
        $where = [];
        if ($id) {
            $where['id'] = $id;  // 假设学校名称字段是 school_name
        }elseif ($name) {
            $where['name'] = ['like', '%' . $name . '%'];  // 假设学校名称字段是 school_name
        }

        // 使用模型进行数据查询，加入条件并分页
        $schools = $schoolModel->where($where)
            ->page($page, $pagesize)  // 每页显示10条记录
            ->select();
        foreach ($schools as $key => $value) {
            $schools[$key]['school_logo'] = getImg($value['school_logo'],124,124);
            $schools[$key]['thumbnail'] = getImg($value['thumbnail'],124,124);
        }

        if ($schools) {
            // 如果查询到学校信息，返回成功响应并携带学校数据
            return $this->success('获取学校列表成功', $schools);
        } else {
            // 如果未查询到，返回相应的错误提示
            return $this->error('暂无学校信息');
        }
    }


    // 获取单个学校信息的方法，接收用户ID作为参数
    public function read($id)
    {
        // 实例化用户模型
        $schoolModel = new SchoolModel();
        // 根据传入的ID查询单个学校信息，可添加更多验证逻辑确保ID合法性等
        $school = $schoolModel->where('id', $id)->find();
        if ($school) {
            return $this->success('获取学校信息成功', $school);
        } else {
            return $this->error('未找到对应ID的学校');
        }
    }

    // 按坐标位置和学校名称搜索学校
    public function list()
    {
        $name = input('get.searchSchool');
        $schoolModel = new SchoolModel();
        if (!empty($name)) {
            $schoolModel->where('name', 'like', '%' . $name . '%');
        }
        $schools = $schoolModel->select();
        foreach ($schools as $key => $value) {
            $schools[$key]['school_logo'] = getImg($value['school_logo'],124,124);
            $schools[$key]['thumbnail'] = getImg($value['thumbnail'],124,124);
            $schools[$key]['message'] = $this->schoolCourse($value['id']);
            $schools[$key]['is_collected'] = $this->isCollected($value['id']);
            if(empty($value['qrcode'])) {
                $schools[$key]['qrcode'] = $this->generateQrcode($value['id'],$value['name'],3);
                $schoolModel->where('id', $value['id'])->update(['qrcode' => $schools[$key]['qrcode']]);
            }

        }

        return $this->success('获取学校列表成功', $schools);
    }

    //该学校有什么课程
    public function schoolCourse($school_id)
    {
        $user=$this->auth->getUser(true);
        $courseDetails = Db::name('course_table_autoplan_temp')
            ->alias('t')
            ->join('fa_course_table tb', 'tb.id=t.table_id', 'INNER')
            ->join('eb_school s', 's.id=tb.school_id', 'INNER')
            ->join('eb_classes c', 'c.id=t.classes_id', 'INNER')
            ->join('fa_ocation o', 'o.id=t.ocation_id', 'INNER')
            ->join('fa_ocation o2', 'o.pid=o2.id', 'INNER')
            ->join('fa_subject_lv sl', 'sl.id=c.subject_lv', 'INNER');
        if ($user) {
            $courseDetails = $courseDetails->join('eb_apply_form_item a', "a.classes_id=c.id and a.user_id='{$user['uid']}'", 'LEFT');
        } else {
            $courseDetails =  $courseDetails->join('eb_apply_form_item a', "a.classes_id=c.id", 'LEFT');
        }
        $courseDetails = $courseDetails->field("
            o.id as ocation_id,
            o.name as ocation_name,
            tb.name as course_name,
            o2.name as parent_location_name,
            o2.id as parent_location_id,
            c.intro as description,
            o.address as address,
            c.description as detail_description,
            o.`longitude`,
            o.`latitude`,
            c.price,
            c.intro,
            c.rel_type,
            c.id as classes_id,
            c.name as classes_name,
            sl.name as subject_name,
            sl.id as subjectlv_id,
            a.id as apply_id,
            c.num - apply_num as remaining_slots
        ")
            ->where('s.id', $school_id)
            ->group("t.ocation_id,t.classes_id")
            ->limit(3)
            ->select();
        $data["courseList"]=$courseDetails;
        $result="该学校报名学习开始了，快来报名吧！";
        foreach ($courseDetails as $key => $value) {
            $result.="有$value[classes_name]，$value[subject_name]课程，还剩$value[remaining_slots]个名额。\n";
        }
        return $result;
    }

    // 学校简介
    public function schoolInfo($school_id)
    {
        if(empty($school_id)||$school_id==0||$school_id==null||$school_id==''||$school_id=='null'||$school_id=='undefined'){
          $school_id=1;
        };
        $schoolInfo = Db::name('eb_school')
            ->where('id', $school_id)
            ->field("
                name,
                address,
                intro,
                id as school_id"
            )->find();
        return $this->success('获取学校信息成功', $schoolInfo);
    }

    public function enrollment($school_id)
    {
        $page = input('get.page', 1);
        $user=$this->auth->getUser(true);
        $courseDetails = Db::name('course_table_autoplan_temp')
            ->alias('t')
            ->join('fa_course_table tb', 'tb.id=t.table_id', 'INNER')
            ->join('eb_school s', 's.id=tb.school_id', 'INNER')
            ->join('eb_classes c', 'c.id=t.classes_id', 'INNER')
            ->join('fa_ocation o', 'o.id=t.ocation_id', 'INNER')
            ->join('fa_ocation o2', 'o.pid=o2.id', 'INNER')
            ->join('fa_subject_lv sl', 'sl.id=c.subject_lv', 'INNER');
        if ($user) {
            $courseDetails = $courseDetails->join('eb_apply_form_item a', "a.classes_id=c.id and a.user_id='{$user['uid']}'", 'LEFT');
        } else {
            $courseDetails =  $courseDetails->join('eb_apply_form_item a', "a.classes_id=c.id", 'LEFT');
        }
            $courseDetails = $courseDetails->field("
            o.id as ocation_id,
            o.name as ocation_name,
            tb.name as course_name,
            o2.name as parent_location_name,
            o2.id as parent_location_id,
            c.intro as description,
            o.address as address,
            c.description as detail_description,
            o.`longitude`,
            o.`latitude`,
            c.price,
            c.intro,
            c.rel_type,
            c.id as classes_id,
            c.name as classes_name,
            sl.name as subject_name,
            sl.id as subjectlv_id,
            a.id as apply_id,
            c.num - apply_num as remaining_slots
        ")
            ->where('s.id', $school_id)
            ->group("t.ocation_id,t.classes_id")
            ->limit($page, $limit = 30)
            ->select();
        return $this->success('获取学校招生信息成功', $courseDetails);
    }

    // 招生详情
    public function enrollmentDetail($classes_id){
        $user=$this->auth->getUser(true);
        $enrollmentDetail = Db::name('course_table_autoplan_temp')
            ->alias('t')
            ->join('fa_course_table tb', 'tb.id=t.table_id', 'INNER')
            ->join('eb_school s', 's.id=tb.school_id', 'INNER')
            ->join('eb_classes c', 'c.id=t.classes_id', 'INNER')
            ->join('fa_ocation o', 'o.id=t.ocation_id', 'INNER')
            ->join('fa_ocation o2', 'o.pid=o2.id', 'INNER')
            ->join('fa_subject_lv sl', 'sl.id=c.subject_lv', 'INNER');
        if ($user) {
            $enrollmentDetail = $enrollmentDetail->join('eb_apply_form_item a', "a.classes_id=c.id and a.user_id='{$user['uid']}'", 'LEFT');
        } else {
            $enrollmentDetail =  $enrollmentDetail->join('eb_apply_form_item a', "a.classes_id=c.id", 'LEFT');
        }
            $enrollmentDetail =  $enrollmentDetail->field("
            o.id as ocation_id,
            o.name as ocation_name,
            tb.name as course_name,
            o2.name as parent_location_name,
            o2.id as parent_location_id,
            c.intro as description,
            o.address as address,
            c.description as detail_description,
            t.create_time,
            o.`longitude`,
            o.`latitude`,
            c.price,
            c.intro,
            c.cover,
            c.rel_type,
            c.id as classes_id,
            c.name as classes_name,
            sl.name as subject_name,
            sl.id as subjectlv_id,
            a.id as apply_id,
            c.num - apply_num as remaining_slots"
            )
            ->where('c.id', $classes_id)
            ->find();
            foreach ($enrollmentDetail as $key => $value) {
                if($key == 'create_time'){
                    $enrollmentDetail[$key] = date('Y年m月d日 H:i', $value);
                }
            }
            return $this->success('获取学校招生信息成功', $enrollmentDetail);
    }

    public function activeDetail($classes_id)
    {
        $user=$this->auth->getUser(true);
        $enrollmentDetail = Db::name('course_table_autoplan_temp')
            ->alias('t')
            ->join('fa_course_table tb', 'tb.id=t.table_id', 'INNER')
            ->join('eb_school s', 's.id=tb.school_id', 'INNER')
            ->join('eb_classes c', 'c.id=t.classes_id', 'INNER')
            ->join('fa_ocation o', 'o.id=t.ocation_id', 'INNER')
            ->join('fa_ocation o2', 'o.pid=o2.id', 'INNER')
            ->join('fa_subject_lv sl', 'sl.id=c.subject_lv', 'INNER');
        if ($user) {
            $enrollmentDetail = $enrollmentDetail->join('eb_apply_form_item a', "a.classes_id=c.id and a.user_id='{$user['uid']}'", 'LEFT');
        } else {
            $enrollmentDetail =  $enrollmentDetail->join('eb_apply_form_item a', "a.classes_id=c.id", 'LEFT');
        }
        $enrollmentDetail = $enrollmentDetail->field("
            o.id as ocation_id,
            o.name as ocation_name,
            tb.name as course_name,
            o2.name as parent_location_name,
            o2.id as parent_location_id,
            c.intro as description,
            o.address as address,
            c.description as detail_description,
            t.create_time,
            o.`longitude`,
            o.`latitude`,
            c.price,
            c.intro,
            c.cover,
            c.rel_type,
            c.id as classes_id,
            c.name as classes_name,
            sl.name as subject_name,
            sl.id as subjectlv_id,
            a.id as apply_id,
            c.apply_num as apply_num,
            c.num,
            c.num - apply_num as remaining_slots"
            )
            ->where('c.id', $classes_id)
            ->find();
        foreach ($enrollmentDetail as $key => $value) {
            if($key == 'create_time'){
                $enrollmentDetail[$key] = date('Y年m月d日 H:i', $value);
            }
        }
        return $this->success('获取学校活动详情成功', $enrollmentDetail);
    }

    // 收藏学校
    public function collectSchool($school_id)
    {
        $user = $this->auth->getUser();
        if(empty($user)){
            return $this->error('请先登录');
        }
        $params = [
            'user_id' => $user['uid'],
            'target_id' => $school_id,
            'school_id' => $school_id,
            'type' => 0
        ];

        return $this->success('收藏成功', empty(Favorites::where($params)->where('delete_time',null)->find()) ? Favorites::create($params) : null);
    }


    public function isCollected($school_id,$collect_type= 0){
        $user=$this->auth->getUser(true);
        if(!$user){
            return false;
        }
        $user_id=$user['uid'];
        try{
            $result=Db::name('favorites')->where(['user_id'=>$user_id,'type'=>$collect_type,'target_id'=>$school_id,'delete_time'=>null])->find();
            if($result){
                return true;
            }else{
                return false;
            }
        }catch(Exception $e){
            return false;
        }
    }

    public function getColumnList(Request $request)
    {
        $school_id = $request->param('id');
        if (empty($school_id)){
            $this->error('学校id有误',[], 400);
        }

        $this->success('获取成功',
            Column::where('school_id', $school_id)
                ->where('status', 1)
                ->where('type', 1)
                ->where('diff', 0)
                ->select(),
            200);
    }

    public function getLicense(Request $request)
    {
        $params = $request->param();

        if (empty($params['school_id'])){
            $this->error('学校id有误',[], 400);
        }
        if (empty($params['phone'])){
            $this->error('搜索不为空',[], 400);
        }
        $user = $this->auth->getUser();
        if ($user['group_id'] != 3){
            $this->error('无权限查找',[], 400);
        }

        $license = Db::name('user_license')
            ->where('school_id',$params['school_id'])
            ->where('phone',$params['phone'])
            ->find();
        if (empty($license)){
            $this->error('暂查询不到相关信息',[], 400);
        }
        $license['license'] = explode(',',$license['license']);
        $this->success('获取成功', $license, 200);
    }

    public function getLicenseImg(Request $request)
    {
        $params = $request->param();

        if (empty($params['school_id'])){
            $this->error('学校id有误',[], 400);
        }
        if (empty($params['user_id'])){
            $this->error('用户ID有误',[], 400);
        }

        $license = Db::name('user_license')
            ->where('school_id',$params['school_id'])
            ->where('user_id',$params['user_id'])
            ->find();
        if (empty($license)){
            $data = [];
        }else{
            $data = empty($license['license']) ? [] : explode(',',$license['license']);
        }

        $this->success('获取成功', $data, 200);
    }

    public function getCourseTable()
    {
        // 准备查询参数
        $params = [
            'page' => 1,
            'limit' => 1000,
            'school_id' => input('school_id'),
            'level1' => input('level1'),
            'level2' => input('level2'),
            'keyword' => input('keyword'),
            'subject_name' => input('subject_name'),
            'subjectlv_id' => input('subjectlv_id'),
            'order' => 'start_date asc,km asc',
            'table_type' => input('table_type'),
            'class_type' => input('class_type'),
            'current_day' => input('current_day'),
        ];
        
        // 使用反射调用Event控制器的baseCourseQuery方法
        $eventClass = new \ReflectionClass('app\api\controller\v1\Event');
        $eventController = $eventClass->newInstanceWithoutConstructor();
        
        // 手动调用父类初始化
        $eventController->_initialize();
        
        // 调用baseCourseQuery方法获取数据
        $data = $eventController->baseCourseQuery($params);
        
        $this->success('查询成功', $data);
    }

    public function getCourseTableList(Request $request)
    {
        $school_id = $request->param('id');
        if (empty($school_id)){
            $this->error('学校id不为空',[], 400);
        }

        $this->success('获取成功', Coursetable::where('school_id',$school_id)->where('status',1)->field('id,school_id,name,start_date,end_date,create_time')->select(), 200);
    }

    public function getCloudClassroom(Request $request)
    {
        $school_id = $request->param('id');
        if (empty($school_id)){
            $this->error('学校id不为空',[], 400);
        }

        $column = Column::where('school_id' ,$school_id)->where('status',1)->where('type',1)->where('diff',1)->select();
        if (empty($column)){
            $this->error('暂无数据',[], 400);
        }

        foreach ($column as $k=>$v){
            $data_column[] = $v['column'];
            $data[]= Article::where('column_id',$v['id'])
                ->where('status', 1)
                ->where('delete_time', null)
                ->field('id,title,cover')
                ->select();
        }

        $this->success('获取成功', ['column'=>$data_column, 'video'=>$data], 200);
    }

    public function getVideo(Request $request)
    {
        $id = $request->param('id');
        if (empty($id)) {
            $this->error('视频id不为空', [], 400);
        }

        $data = Article::where('id',$id)->field('title,content,video')->find();
        if (empty($data)){
            $this->error('暂无数据',[], 400);
        }

        $this->success('获取成功', $data, 200);
    }
    public function getprameter(Request $request)
    {
        $params = $request->param();
        $params["timestamp"] = date("Y-m-d H:i:s",time());
        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../runtime/log/scene_debug.log",
            "接收到的参数: " . json_encode($params, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);
        $this->success('获取成功', $params, 200);
    }
}